#include "at32f415_board.h"
#include "at32f415_clock.h"

#include "dap_main.h"
#include "drv_usb2uart.h"
#include "drv_led.h"

#include "user_param.h"

static void app_wdtinit(void)
{
  /* disable register write protection */
  wdt_register_write_enable(TRUE);

  /* set the wdt divider value */
  wdt_divider_set(WDT_CLK_DIV_32);

  /* set reload value

   timeout = reload_value * (divider / lick_freq )    (s)

   lick_freq    = 40000 Hz
   divider      = 4
   reload_value = 3000

   timeout = 2500 * (32 / 40000 ) = 2s
  */
  wdt_reload_value_set(1250 - 1);

  /* reload wdt counter */
  wdt_counter_reload();
  
  /* enable wdt */
  wdt_enable();
}

int main(void)
{
    system_clock_config();
    nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
    delay_init();
    
    led_init();
    LED_PWR_ON();
    
    user_param_init();
    
    usart2_preinit();
    usart3_preinit();
    
    chry_dap_init();
    
    app_wdtinit();
    
    while(1)
    {
        wdt_counter_reload();
        chry_dap_handle();
        chry_dap_usb2uart_rx(&usart2_state);
        chry_dap_usb2uart_handle(&usart2_state);
        chry_dap_usb2uart_rx(&usart3_state);
        chry_dap_usb2uart_handle(&usart3_state);
//        chry_dap_hid_handle();
    }
}
